﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wicresoft.SMS.Web.Models;
using Wicresoft.SMS.Data;
using Wicresoft.SMS.Common;

namespace Wicresoft.SMS.Web.Controllers
{
    public class ReportController : CustomBaseController
    {
        //
        // GET: /Report/

        public ActionResult Index()
        {
            return View();
        }

        [CustomAuthorise(Flag = AuthoriseFlag.page_usermanage)]
        public ActionResult Overview()
        {
            OverViewReportModel model = new OverViewReportModel();
            WebConfigProvider configProvider = new WebConfigProvider();
            model.StartDate = configProvider.SystemStartDate;
            TimeSpan ts = DateTime.Now - Convert.ToDateTime(configProvider.SystemStartDate);
            model.TotalRunTime =Convert.ToString(ts.Days) +" "+Convert.ToString(App_GlobalResources.Resources.Report_OverView_Day) +" "+ Convert.ToString(ts.Hours) +" "+ Convert.ToString(App_GlobalResources.Resources.Report_OverView_Hour)
                +" "+ Convert.ToString(ts.Minutes) +" "+ Convert.ToString(App_GlobalResources.Resources.Report_OverView_Minute);
           // model.TotalRunTime = string.Format("{0}天{1}小时{2}分钟", ts.Days, ts.Hours, ts.Minutes);
            IReportWebDataAccess dataAccess = new sqlReportWebDataAccess(configProvider.ConnectionString);
            model.TotalMessage = dataAccess.GetTotalMessage(Convert.ToDateTime(configProvider.SystemStartDate));
            model.TotalFailedMessage = dataAccess.GetTotalFaliedMessage(Convert.ToDateTime(configProvider.SystemStartDate));
            model.TotalMoney = model.TotalMessage * Convert.ToDouble(configProvider.Price);
            return View(model);
        }

        [CustomAuthorise(Flag = AuthoriseFlag.page_usermanage)]
        public ActionResult History(HistoryReportModel Model)
        {
            WebConfigProvider configProvider = new WebConfigProvider();
            IReportWebDataAccess dataAccess = new sqlReportWebDataAccess(configProvider.ConnectionString);
            if (String.IsNullOrEmpty(Request.QueryString["starttime"]) || String.IsNullOrEmpty(Request.QueryString["endtime"]))
            {
                Model.StartTime = DateTime.Today.AddDays(-7);
                Model.EndTime = DateTime.Today;
                Model.Frequence = queryFrequence.day;
            }
            SelectList ListItems = new SelectList(SelectFrequenc.SelectItems().AsEnumerable(), "Value", "Text");
            ViewData["ListItems"] = ListItems;
            List<HistoryReport> report = dataAccess.QueryHistoryReport(Model.StartTime, Model.EndTime.AddDays(1).AddMinutes(-1), Model.Frequence);

            System.Web.UI.DataVisualization.Charting.SeriesChartType chartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Line;
            Model.ImageSource = ReportHelper.GetImageRoute(WebReport.ChageReportModel(report), chartType, Model.StartTime, Model.EndTime, null);

            return View(Model);
        }

        [CustomAuthorise(Flag = AuthoriseFlag.page_usermanage)]
        public ActionResult Group(GroupReportModel Model)
        {
            WebConfigProvider configProvider = new WebConfigProvider();
            IReportWebDataAccess dataAccess = new sqlReportWebDataAccess(configProvider.ConnectionString);
            if (String.IsNullOrEmpty(Request.QueryString["starttime"]) || String.IsNullOrEmpty(Request.QueryString["endtime"]))
            {
                Model.StartTime = DateTime.Today.AddDays(-7);
                Model.EndTime = DateTime.Today;
                Model.MaxShow = 10;
            }
            SelectList ListItems = new SelectList(SelectFrequenc.MaxShowItems().AsEnumerable(), "Value", "Text");
            ViewData["MaxItems"] = ListItems;
            List<GroupReport> report = dataAccess.QueryGroupReport(Model.StartTime, Model.EndTime.AddDays(1), Model.MaxShow);

            System.Web.UI.DataVisualization.Charting.SeriesChartType chartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Pie;
            Model.ImageSource = ReportHelper.GetImageRoute(WebReport.ChageReportModel(report), chartType, Model.StartTime, Model.EndTime, "GroupReport");
            return View(Model);
        }

        [CustomAuthorise(Flag = AuthoriseFlag.page_usermanage)]
        public ActionResult User(UserReportModel Model)
        {
            WebConfigProvider configProvider = new WebConfigProvider();
            IReportWebDataAccess dataAccess = new sqlReportWebDataAccess(configProvider.ConnectionString);
            if (String.IsNullOrEmpty(Request.QueryString["starttime"]) || String.IsNullOrEmpty(Request.QueryString["endtime"]))
            {
                Model.StartTime = DateTime.Today.AddDays(-7);
                Model.EndTime = DateTime.Today;
                Model.MaxShow = 10;
            }
            SelectList ListItems = new SelectList(SelectFrequenc.MaxShowItems().AsEnumerable(), "Value", "Text");
            ViewData["MaxItems"] = ListItems;
            List<IndividualReprot> report = dataAccess.QueryIndividualReprot(Model.GroupId, Model.StartTime.AddDays(1), Model.EndTime, Model.MaxShow);
            string GroupName = string.Empty;
            if (Model.GroupId != 0)
                GroupName = dataAccess.GetDepartnameById(Model.GroupId);
            else
                GroupName = "0";
            System.Web.UI.DataVisualization.Charting.SeriesChartType chartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Pie;
            Model.ImageSource = ReportHelper.GetImageRoute(WebReport.ChageReportModel(report), chartType, Model.StartTime, Model.EndTime, GroupName);
            return View(Model);
        }

        [CustomAuthorise(Flag = AuthoriseFlag.page_usermanage)]
        public ActionResult UsersReport(UsersReportModel Model)
        {
            if (Model.Page == 0)
            {
                Model.Page = 1;
            }
            if (Model.key == null)
            {
                Model.key = "";
            }
            if (Model.orderby == null)
            {
                Model.orderby = "";
            }
            WebConfigProvider configProvider = new WebConfigProvider();
            IReportWebDataAccess dataAccess = new sqlReportWebDataAccess(configProvider.ConnectionString);
            int max = Convert.ToInt32(configProvider.MaxshowInHistory);
            if (String.IsNullOrEmpty(Request.QueryString["starttime"]) || String.IsNullOrEmpty(Request.QueryString["endtime"]))
            {
                Model.startTime = DateTime.Today.AddDays(-7);
                Model.endTime = DateTime.Today;
            }
            //DateTime starttime = Convert.ToDateTime("2010-01-24");
            //DateTime endtime = DateTime.Now;
            int sort = 0;
            if (Model.orderby == "desc")
                sort = 1;
            if (Model.orderby == "asc")
                sort = 2;

            Model.infos = dataAccess.QueryUsesrReports(Model.key, Model.Page, max, Model.startTime, Model.endTime, sort);
            Model.maxpages = dataAccess.UserInfoPage(max, Model.key);
            return View(Model);
        }

        [CustomAuthorise(Flag = AuthoriseFlag.page_usermanage)]
        public ActionResult ExportUsersInfo(string start,string end)
        {
            DateTime starts = new DateTime();
            DateTime ends = new DateTime();
            if (start == null)
            {
                starts = DateTime.Today.AddDays(-7);
            }
            else
            {
                starts = Convert.ToDateTime(start);
            }
            if (end == null)
            {
                ends = DateTime.Today;
            }
            else
            {
                ends =Convert.ToDateTime(end);
            }
            WebConfigProvider configProvider = new WebConfigProvider();
            IReportWebDataAccess dataAccess = new sqlReportWebDataAccess(configProvider.ConnectionString);
            System.Web.UI.WebControls.GridView gv = new System.Web.UI.WebControls.GridView();
            gv.DataSource = dataAccess.Getdata(Convert.ToDateTime(starts),Convert.ToDateTime(ends));
            //Convert.ToDateTime(Request.QueryString["starttime"]),Convert.ToDateTime(Request.QueryString["endtime"])
            gv.DataBind();

            //代码来源 http://blog.csdn.net/zhoufoxcn/archive/2008/05/16/2450642.aspx
            Response.Clear();
            Response.BufferOutput = true;
            //设定输出的字符集
            Response.Charset = "UTF-8";
            //假定导出的文件名为FileName.xls
            Response.AppendHeader("Content-Disposition", "attachment;filename=exportusersinfo.xls");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            //设置导出文件的格式
            Response.ContentType = "application/ms-excel";
            //关闭ViewState
            // EnableViewState = false;
            System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter stringWriter = new System.IO.StringWriter(cultureInfo);
            System.Web.UI.HtmlTextWriter textWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
            gv.RenderControl(textWriter);
            //把HTML写回浏览器
            Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=UTF-8\">");
            Response.Write(stringWriter.ToString());
            Response.End();

            return View();
        }
    }
}
